#include "ap3216c.h"
#include <stdio.h>

void AP3216_Write_Data(uint_fast8_t registerAddr, uint_fast8_t val) {
  // 1.主机向从机发送开始信号
  IIC_Start();
  // 2.发送从机地址
  IIC_Write_Data(AP3216_WRITE_ADDRESS);
  // 3.主机等待从机应答信号
  int ret = IIC_Read_ACK();
  if (ret == -1) {
    return;
  }
  // 4.发送寄存器地址
  IIC_Write_Data(registerAddr);
  ret = IIC_Read_ACK();
  if (ret == -1) {
    return;
  }
  // 5.向相应的寄存器写数据
  IIC_Write_Data(val);
  ret = IIC_Read_ACK();
  if (ret == -1) {
    return;
  }
  // 6.发送停止信号
  IIC_Stop();
}

uint_fast8_t AP3216_Read_Data(uint_fast8_t registerAddr) {
  // 1.主机向从机发送开始信号
  uint_fast8_t data;
  IIC_Start();
  // 2.发送从机地址
  IIC_Write_Data(AP3216_WRITE_ADDRESS);
  // 3.主机等待从机应答信号
  int ret = IIC_Read_ACK();
  if (ret == -1) {
    return 0;
  }
  // 4.发送寄存器地址
  IIC_Write_Data(registerAddr);
  // 5.主机等待从机应答信号
  ret = IIC_Read_ACK();
  if (ret == -1) {
    return 0;
  }
  // 6.主机向从机发送开始信号
  IIC_Start();
  // 7.发送从机地址
  IIC_Write_Data(AP3216_READ_ADDRESS);
  // 8.读取数据
  ret = IIC_Read_ACK();
  if (ret == -1) {
    return 0;
  }
  data = IIC_Read_Data();
  // 9.发送NASK信号
  IIC_Write_NACK();
  // 10..发送停止信号
  IIC_Stop();
  return data;
}

// 配置ap3216传感器
void AP3216_Config() {
  // 复位
  AP3216_Write_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS, 0x04);
  // 2.激活 ALS + PS+IR
  AP3216_Write_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS, 0x03);
  // IIC_DELAY_MS(10);
  // 3.读取
  uint_fast8_t ret =
      AP3216_Read_Data(AP3216_SYSTEM_CONFIGRATION_ADDRESS);
  if (ret == 0x03) {
    printf("  ap3216 communication success!\r\n");
  }
}

// 读取ALS的数据 光
uint_fast16_t AP3216_Read_ALS() {
  // 3.读取数据
  uint_fast16_t data = 0;
  uint_fast8_t data_low =
      AP3216_Read_Data(AP3216_ALS_DATA_LOW_ADDRESS);
  uint_fast8_t data_high =
      AP3216_Read_Data(AP3216_ALS_DATA_HIGH_ADDRESS);
  data = data_high << 8 | data_low;
  return data;
}

// 读取PS的数据 距离
uint_fast16_t AP3216_Read_PS() {
  // 3.读取数据
  uint_fast16_t data = 0;
  uint_fast8_t data_low =
      AP3216_Read_Data(AP3216_PS_DATA_LOW_ADDRESS);
  uint_fast8_t data_high =
      AP3216_Read_Data(AP3216_PS_DATA_HIGH_ADDRESS);
  data = data_high & (0x3f);
  data <<= 4;
  data |= ((data_low) & 0xf);
  return data;
}
